package com.ias.agdis_r.adapter;

import android.content.Context;
import android.graphics.Color;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.ias.agdis_r.R;
import com.ias.agdis_r.activity.MainActivity;
import com.ias.agdis_r.bean.task.Task;
import com.ias.agdis_r.bean.user.UserInfoBean;
import com.ias.agdis_r.manager.DataManager;
import com.ias.agdis_r.manager.JavaBeanManager;
import com.ias.agdis_r.module.MessageModel;
import com.ias.agdis_r.util.S;
import com.ias.agdis_r.util.TaskUtil;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;


public class FTaskGridViewAdapter extends BaseAdapter {

    private Context context = null;
    private LayoutInflater inflater = null;
    public Map<Integer, String> tnbMap = new HashMap<Integer, String>(); // 键为LIST的postion,值为任务的tnb
    private LinkedHashMap<String, Task> taskLinkedMap = null;
    List<Entry<String, Task>> taskList = null;
    public boolean isHistroy = false;
    private boolean flag_multiselect = false; // 移交多选模式
    private HashMap<Task,Boolean> multiselectMap = new HashMap<Task,Boolean>();// 保存任务移交多选结果
    private boolean flag_singlchoice = false; // 转发单选模式
    private HashMap<Task,Boolean> singlchoiceMap = new HashMap<Task,Boolean>();// 保存任务转发单选结果
    private int SORT_TYPE = -1;                      //未选择排序方式

    public FTaskGridViewAdapter(Context context, boolean his, boolean forward) {
        this.context = context;
        this.isHistroy = his;
        initData();
        // 初始化TNB的MAP
        initTnbMap();
        sort();
    }

    private void initData() {
        if (isHistroy) {
            taskLinkedMap = DataManager.getInstance().getTaskHistroyWorkList();
        } else {
            taskLinkedMap = DataManager.getInstance().getWorkTaskList();
            // ReceiveTaskList与WorkTaskList合并显示
            taskLinkedMap.putAll(DataManager.getInstance().getReceiveTaskList());
        }
    }


    private void initTnbMap() {
        tnbMap.clear();
        Set<String> tnbSet = taskLinkedMap.keySet();
        int i = 0;
        for (String tnb : tnbSet) {
            tnbMap.put(i, tnb);
            i++;
        }
    }

    public final class ViewHolder {
        public TextView txtHangbanhao, txtJihao, txtJiwei, txtJiXing,
                txtShijian, txtTaskNo, txtFke, txtNum,txtPnm,txtTTR;
        public ImageView iconPnm,// 状态图片
                iconAdid, // 进离港图片
                iconType;// 岗位类型图片
        public LinearLayout parent;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        ViewHolder holder = new ViewHolder();
        if (convertView == null) {// 如果加载item布局为null
            inflater = LayoutInflater.from(context);
            convertView = inflater.inflate(R.layout.item_task_flight_list_grid, null);// 设置加载布局
            holder.iconAdid = (ImageView) convertView
                    .findViewById(R.id.iconAdid);
            holder.txtHangbanhao = (TextView) convertView
                    .findViewById(R.id.txt_HangBanHao);
            holder.txtJihao = (TextView) convertView
                    .findViewById(R.id.txt_JiHao);
            holder.txtJiwei = (TextView) convertView
                    .findViewById(R.id.txt_JiWei);
            holder.txtJiXing = (TextView) convertView
                    .findViewById(R.id.txt_JiXing);
            holder.txtShijian = (TextView) convertView
                    .findViewById(R.id.txt_ShiJian);
            holder.txtPnm = (TextView) convertView.findViewById(R.id.txt_PNM);
            holder.txtNum = (TextView) convertView.findViewById(R.id.txt_NUM);
            holder.txtTTR = (TextView) convertView.findViewById(R.id.txt_TTR);
            holder.parent = (LinearLayout) convertView.findViewById(R.id.ll_parent);
            convertView.setTag(holder);
        } else {
            holder = (ViewHolder) convertView.getTag();
        }
        // 加载数据
        Task task = taskLinkedMap.get(tnbMap.get(position));
        if (task != null) {
            // 进离港图标
            if (S.valueOf(task.getTaskInfo().getAOD()).equals("A")) {
                holder.iconAdid.setBackgroundResource(R.drawable.adida_red);
            } else {
                holder.iconAdid.setBackgroundResource(R.drawable.adidd);
            }
            holder.txtHangbanhao
                    .setText(S.valueOf(task.getTaskInfo().getFLN()));
            holder.txtJihao.setText(context.getString(R.string.num)
                    + S.valueOf(task.getTaskInfo().getREG()));
            holder.txtJiwei.setText(context.getString(R.string.place)
                    + S.valueOf(task.getTaskInfo().getPSN()));
            holder.txtJiXing.setText(context.getString(R.string.type)
                    + S.valueOf(task.getTaskInfo().getACN()));

            String sLatesetTimew = TaskUtil.getFlightLatestTime(
                    S.valueOf(task.getTaskInfo().getATO()),
                    S.valueOf(task.getTaskInfo().getETO()),
                    S.valueOf(task.getTaskInfo().getSTO()));
            holder.txtShijian.setText(context.getString(R.string.time) + S.FormatTime2(sLatesetTimew));
            String text = S.valueOf(task.getTaskInfo().getSTN());
            if (S.isNotEmpty(text)) {
                if (text.equals(context.getString(R.string.paifa))) {
                    holder.txtPnm.setText(context.getString(R.string.unaccept));
                    holder.txtPnm.setBackgroundResource(R.drawable.textview_pnm_background2);
                    holder.txtNum.setBackgroundResource(R.drawable.textview_num_background2);
                } else if (MessageModel.TCXX.equals(task.getPID()) || MessageModel.TRJT.equals(task.getPID()) || MessageModel.TEND.equals(task.getPID()) || MessageModel.T_QJHS_YQ.equals(task.getPID()) || MessageModel.TTRN.equals(task.getPID())) {
                    holder.txtPnm.setText(text);
                    holder.txtPnm.setBackgroundResource(R.drawable.textview_pnm_background3);
                    holder.txtNum.setBackgroundResource(R.drawable.textview_num_background3);
                } else {
                    holder.txtPnm.setText(text);
                    holder.txtPnm.setBackgroundResource(R.drawable.textview_pnm_background);
                    holder.txtNum.setBackgroundResource(R.drawable.textview_num_background);
                }
            } else {
                text = S.valueOf(task.getProcess(task.getPID()).getPCNM());
                if (text.equals(context.getString(R.string.paifa))) {
                    holder.txtPnm.setText(context.getString(R.string.unaccept));
                    holder.txtPnm.setBackgroundResource(R.drawable.textview_pnm_background2);
                    holder.txtNum.setBackgroundResource(R.drawable.textview_num_background2);
                    holder.txtNum.setTextColor(context.getResources().getColor(R.color.warning));
                } else if (MessageModel.TCXX.equals(task.getPID()) || MessageModel.TRJT.equals(task.getPID()) || MessageModel.TEND.equals(task.getPID()) || MessageModel.T_QJHS_YQ.equals(task.getPID()) || MessageModel.TTRN.equals(task.getPID())) {
                    holder.txtPnm.setText(text);
                    holder.txtPnm.setBackgroundResource(R.drawable.textview_pnm_background3);
                    holder.txtNum.setBackgroundResource(R.drawable.textview_num_background3);
                    holder.txtNum.setTextColor(context.getResources().getColor(R.color.success));
                } else {
                    holder.txtPnm.setText(text);
                    holder.txtPnm.setBackgroundResource(R.drawable.textview_pnm_background);
                    holder.txtNum.setBackgroundResource(R.drawable.textview_num_background);
                    holder.txtNum.setTextColor(context.getResources().getColor(R.color.info));
                }
            }
            holder.txtNum.setText(S.valueOf(position+1));

            String ttr = task.getTaskInfo().getTTR();
            String cpc = task.getTaskInfo().getCPC();
            String pid = task.getPID();
            String eto = task.getTaskInfo().getETO();
            String label = "";
            int backgroundId = R.color.transparent;
            if (!MessageModel.TDWN.equals(pid) && !MessageModel.TEND.equals(pid)
                    && !MessageModel.TRJT.equals(pid)
                    && !MessageModel.TCXX.equals(pid)) {
                // G：转发
                if (checkTaskForward(task)) {
                    label = context.getString(R.string.sendto1);
                    if (text.equals(context.getString(R.string.sentto))) {
                        backgroundId = R.drawable.textview_background6;
                    } else {
                        backgroundId = R.drawable.textview_background4;
                    }
                    // T：移交
                } else if (checkTaskTransfer(task)) {
                    label = context.getString(R.string.transfer1);
                    backgroundId = R.drawable.textview_background5;
                    // K：进港航班开始之后不能移交
                } else if (checkTaskTTRK(task)) {
                    label = context.getString(R.string.sendto1);
                    backgroundId = R.drawable.textview_background4;
                }
            }
            holder.txtTTR.setText(label);
            holder.txtTTR.setBackgroundResource(backgroundId);
            if(S.isNotEmpty(eto))   //如果有变更时间，变颜色显示
            {
                holder.parent.setBackgroundColor(Color.rgb(255, 182, 193));
            }else {
                holder.parent.setBackgroundColor(Color.WHITE);
            }

            if (flag_multiselect && (MessageModel.ZFYJ_TYPE_T.equals(ttr) || (MessageModel.ZFYJ_TYPE_C.equals(ttr) && !TaskUtil.checkNodeBeforeCurrent(task, cpc))) && !text.equals(context.getString(R.string.paifa))) {
                Boolean isCheck = multiselectMap.get(task);
                if (null != isCheck && true == isCheck) {
                    //holder.parent.setBackgroundColor(Color.rgb(255, 241, 201));
                    holder.parent.setBackgroundResource(R.drawable.task_check);
                } else {
                    holder.parent.setBackgroundColor(Color.WHITE);
                }
            } else if (flag_singlchoice && (MessageModel.ZFYJ_TYPE_G.equals(ttr) || (MessageModel.ZFYJ_TYPE_C.equals(ttr) && TaskUtil.checkNodeBeforeCurrent(task, cpc)) || (MessageModel.ZFYJ_TYPE_K.equals(ttr) && TaskUtil.checkNodeBeforeCurrent(task, cpc))) && !text.equals(context.getString(R.string.paifa))) {
                Boolean isCheck = singlchoiceMap.get(task);
                if (null != isCheck && true == isCheck) {
                    //holder.parent.setBackgroundColor(Color.rgb(255, 241, 201));
                    holder.parent.setBackgroundResource(R.drawable.task_check);
                } else {
                    holder.parent.setBackgroundColor(Color.WHITE);
                }
            }else if(flag_multiselect||flag_singlchoice){
                holder.parent.setBackgroundResource(R.drawable.task_ban_check);
            }
        }

        return convertView;
    }

    /**
     * 设置可以多选
     */
    public void setMultiselect(boolean flag_multiselect){
        this.flag_multiselect = flag_multiselect;
        if (!flag_multiselect) {
            multiselectMap.clear();
        }
        this.notifyDataSetChanged();
    }

    public boolean isMultiselect(){
        return flag_multiselect;
    }

    /**
     * 设置可以单选
     */
    public void setSinglchoice(boolean flag_singlchoice){
        this.flag_singlchoice = flag_singlchoice;
        if (!flag_singlchoice) {
            singlchoiceMap.clear();
        }
        this.notifyDataSetChanged();
    }

    public boolean isSinglchoice(){
        return flag_singlchoice;
    }


    public void setTransferCheck(int position, boolean flag) {
        Task item = getItem(position);
        if (null != item) {
            String pcnm = S.valueOf(item.getProcess(item.getPID()).getPCNM());
            String ttr = item.getTaskInfo().getTTR();
            String cpc = item.getTaskInfo().getCPC();
            if ((MessageModel.ZFYJ_TYPE_T.equals(ttr) || (MessageModel.ZFYJ_TYPE_C.equals(ttr) && !TaskUtil.checkNodeBeforeCurrent(item, cpc))) && !pcnm.equals(context.getString(R.string.paifa))) {
                multiselectMap.put(getItem(position), flag);
            }
            this.notifyDataSetChanged();
        }
    }

    public void setSendtoCheck(int position, boolean flag) {
        Task item = getItem(position);
        if (null != item) {
            String pcnm = S.valueOf(item.getProcess(item.getPID()).getPCNM());
            String ttr = item.getTaskInfo().getTTR();
            String cpc = item.getTaskInfo().getCPC();
            if ((MessageModel.ZFYJ_TYPE_G.equals(ttr) || (MessageModel.ZFYJ_TYPE_C.equals(ttr) && TaskUtil.checkNodeBeforeCurrent(item, cpc)) || ((MessageModel.ZFYJ_TYPE_K.equals(ttr) && TaskUtil.checkNodeBeforeCurrent(item, cpc)))) && !pcnm.equals(context.getString(R.string.paifa))) {
                singlchoiceMap.clear();
                singlchoiceMap.put(getItem(position), flag);
            }
            this.notifyDataSetChanged();
        }
    }

    public boolean getIsTransferCheck(int position){
        if(null != multiselectMap.get(getItem(position))){
            return multiselectMap.get(getItem(position));
        }else{
            return false;
        }
    }

    public boolean getIsSendtoCheck(int position){
        if(null != singlchoiceMap.get(getItem(position))){
            return singlchoiceMap.get(getItem(position));
        }else{
            return false;
        }
    }

    public List<Task> getSinglchoiceList(){
        List<Task> list = new ArrayList<Task>();
        Iterator<Entry<Task, Boolean>> iterator = singlchoiceMap.entrySet().iterator();
        //获取选中项
        while(iterator.hasNext()){
            Entry<Task, Boolean> entry = iterator.next();
            if(entry.getValue()){
                list.add(entry.getKey());
            }
        }
        return list;
    }

    public List<Task> getMultiselectList(){
        List<Task> list = new ArrayList<Task>();
        Iterator<Entry<Task, Boolean>> iterator = multiselectMap.entrySet().iterator();
        //获取选中项
        while(iterator.hasNext()){
            Entry<Task, Boolean> entry = iterator.next();
            if(entry.getValue()){
                list.add(entry.getKey());
            }
        }
        return list;
    }

    public String getTNB(int position) {
        return tnbMap.get(position);
    }

    @Override
    public int getCount() {
        return taskLinkedMap.size();
    }

    @Override
    public Task getItem(int position) {
        String tnb = tnbMap.get(position);
        Task task = taskLinkedMap.get(tnb);
        return task;
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    public void setSortType(int type) {
        this.SORT_TYPE = type;
    }

    public int getSortType() {
        return this.SORT_TYPE;
    }

    @Override
    public void notifyDataSetChanged() {
        initData();
        //排序
        sort();
        super.notifyDataSetChanged();
        //重置是否包含转发移交标记
        if (!"N".equals(JavaBeanManager.getInstance().getUserinfo().getTtr())){
            MainActivity.hasTTRTask[0] = false;
            MainActivity.hasTTRTask[1] = false;
            for (Task task : taskLinkedMap.values()){
                if (task.getTaskInfo().getTTR().equals(MessageModel.ZFYJ_TYPE_T)){
                    MainActivity.hasTTRTask[1] = true;
                }else if (task.getTaskInfo().getTTR().equals(MessageModel.ZFYJ_TYPE_G)){
                    MainActivity.hasTTRTask[0] = true;
                }else if (task.getTaskInfo().getTTR().equals(MessageModel.ZFYJ_TYPE_C)){
                    MainActivity.hasTTRTask[0] = true;
                    MainActivity.hasTTRTask[1] = true;
                }else if (task.getTaskInfo().getTTR().equals(MessageModel.ZFYJ_TYPE_K)){
                    MainActivity.hasTTRTask[0] = true;
                }
                if (MainActivity.hasTTRTask[0] == true && MainActivity.hasTTRTask[1] == true){
                    break;
                }
            }
        }
    }

    private void sort() {
        if (SORT_TYPE == -1) {
            //初始化TNB的MAP
            initTnbMap();
            return;
        }
        taskList = new ArrayList<Entry<String, Task>>(taskLinkedMap.entrySet());
        for (Entry<String, Task> entry : taskList) {
            Log.i("任务列表-排序", "排序前：" + entry.getKey() + "|" + TaskUtil.getFlightLatestTime(S.valueOf(entry.getValue().getTaskInfo().getATO()), S.valueOf(entry.getValue().getTaskInfo().getETO()), S.valueOf(entry.getValue().getTaskInfo().getSTO())));
        }

        //通过比较器实现比较排序
        Collections.sort(taskList, new Comparator<Entry<String, Task>>() {
            public int compare(Entry<String, Task> o1, Entry<String, Task> o2) {

                Task task1 = o1.getValue();
                Task task2 = o2.getValue();
                String eto1 = task1.getTaskInfo().getETO();
                String eto2 = task2.getTaskInfo().getETO();
                String com1 = "";
                String com2 = "";
                switch (SORT_TYPE) {

                    case TaskUtil.SORT_TIME_ASC:     //时间升序
                        com1 = TaskUtil.getFlightLatestTime(S.valueOf(task1.getTaskInfo().getATO()), S.valueOf(task1.getTaskInfo().getETO()), S.valueOf(task1.getTaskInfo().getSTO()));
                        com2 = TaskUtil.getFlightLatestTime(S.valueOf(task2.getTaskInfo().getATO()), S.valueOf(task2.getTaskInfo().getETO()), S.valueOf(task2.getTaskInfo().getSTO()));
                        break;
                    case TaskUtil.SORT_TIME_DESC:     //时间降序
                        com1 = TaskUtil.getFlightLatestTime(S.valueOf(task2.getTaskInfo().getATO()), S.valueOf(task2.getTaskInfo().getETO()), S.valueOf(task2.getTaskInfo().getSTO()));
                        com2 = TaskUtil.getFlightLatestTime(S.valueOf(task1.getTaskInfo().getATO()), S.valueOf(task1.getTaskInfo().getETO()), S.valueOf(task1.getTaskInfo().getSTO()));
                        break;
                    case TaskUtil.SORT_FLN_ASC:         //航班号升序
                        com1 = S.valueOf(task1.getTaskInfo().getFLN());
                        com2 = S.valueOf(task2.getTaskInfo().getFLN());
                        break;
                    case TaskUtil.SORT_FLN_DESC:     //航班号降序
                        com1 = S.valueOf(task2.getTaskInfo().getFLN());
                        com2 = S.valueOf(task1.getTaskInfo().getFLN());
                        break;
                    case TaskUtil.SORT_PSN_ASC:         //机位升序
                        com1 = S.valueOf(task1.getTaskInfo().getPSN());
                        com2 = S.valueOf(task2.getTaskInfo().getPSN());
                        break;
                    case TaskUtil.SORT_PSN_DESC:         //机位降序
                        com1 = S.valueOf(task2.getTaskInfo().getPSN());
                        com2 = S.valueOf(task1.getTaskInfo().getPSN());
                        break;
                    case TaskUtil.SORT_STATE_ASC:      //任务状态升序
                        com1 = S.valueOf(task1.getProcess(task1.getPID()).getPIDX());
                        com2 = S.valueOf(task2.getProcess(task2.getPID()).getPIDX());
                        break;
                    case TaskUtil.SORT_STATE_DESC:      //任务状态降序
                        com1 = S.valueOf(task2.getProcess(task2.getPID()).getPIDX());
                        com2 = S.valueOf(task1.getProcess(task1.getPID()).getPIDX());
                        break;
                    case TaskUtil.SORT_REG_ASC:          //机号升序
                        com1 = S.valueOf(task1.getTaskInfo().getREG());
                        com2 = S.valueOf(task2.getTaskInfo().getREG());
                        break;
                    case TaskUtil.SORT_REG_DESC:      //机号降序
                        com1 = S.valueOf(task2.getTaskInfo().getREG());
                        com2 = S.valueOf(task1.getTaskInfo().getREG());
                        break;
                    case TaskUtil.SORT_ACN_ASC:          //机型升序
                        com1 = S.valueOf(task1.getTaskInfo().getACN());
                        com2 = S.valueOf(task2.getTaskInfo().getACN());
                        break;
                    case TaskUtil.SORT_ACN_DESC:       //机型降序
                        com1 = S.valueOf(task2.getTaskInfo().getACN());
                        com2 = S.valueOf(task1.getTaskInfo().getACN());
                        break;
                    case TaskUtil.SORT_TYPE_ASC:       //任务类型升序
                        com1 = S.valueOf(task1.getTaskInfo().getRNM());
                        com2 = S.valueOf(task2.getTaskInfo().getRNM());
                        break;
                    case TaskUtil.SORT_TYPE_DESC:       //任务类型降序
                        com1 = S.valueOf(task2.getTaskInfo().getRNM());
                        com2 = S.valueOf(task1.getTaskInfo().getRNM());
                        break;
                }
                if(SORT_TYPE%2!=0) {//如果是降序
                    //将有变更时间任务放到前面
                    if (S.isNotEmpty(eto2) && S.isEmpty(eto1)) {
                        return 1;
                    } else if (S.isNotEmpty(eto1) && S.isEmpty(eto2)) {
                        return -1;
                    }
                }else {//如果是升序
                    //将有变更时间任务放到前面
                    if (S.isNotEmpty(eto1) && S.isEmpty(eto2)) {
                        return -1;
                    } else if (S.isEmpty(eto2) && S.isNotEmpty(eto1)) {
                        return 1;
                    }
                }
                return com1.compareTo(com2);
            }
        });
        tnbMap.clear();
        int i = 0;
        for (Entry<String, Task> entry : taskList) {
            String tnb = entry.getValue().getTNB();
            tnbMap.put(i, tnb);
            i++;
            Log.i("任务列表-排序", "排序后：" + entry.getKey() + "|" + TaskUtil.getFlightLatestTime(S.valueOf(entry.getValue().getTaskInfo().getATO()), S.valueOf(entry.getValue().getTaskInfo().getETO()), S.valueOf(entry.getValue().getTaskInfo().getSTO())));
        }
    }

    private boolean checkTaskForward(Task task) {
        String ttr = task.getTaskInfo().getTTR();
        String cpc = task.getTaskInfo().getCPC();
        if (MessageModel.ZFYJ_TYPE_C.equals(ttr) && S.isNotEmpty(cpc)) {
            if (TaskUtil.checkNodeBeforeCurrent(task, cpc)) {
                return true;
            }
        } else if (MessageModel.ZFYJ_TYPE_G.equals(ttr)) {
            return true;
        }
        return false;
    }

    private boolean checkTaskTransfer(Task task) {
        String ttr = task.getTaskInfo().getTTR();
        String cpc = task.getTaskInfo().getCPC();
        if (MessageModel.ZFYJ_TYPE_C.equals(ttr) && S.isNotEmpty(cpc)) {
            if (!TaskUtil.checkNodeBeforeCurrent(task, cpc)) {
                return true;
            }
        } else if (MessageModel.ZFYJ_TYPE_T.equals(ttr)) {
            return true;
        }
        return false;
    }

    private boolean checkTaskTTRK(Task task) {
        String ttr = task.getTaskInfo().getTTR();
        String cpc = task.getTaskInfo().getCPC();
        UserInfoBean userInfo = JavaBeanManager.getInstance().getUserinfo();
        // 进港航班TTR=K,且用户可转可移
        if (MessageModel.ZFYJ_TYPE_K.equals(ttr) && S.isNotEmpty(cpc)) {
            // 该节点及该节点后禁止移交
            if (TaskUtil.checkNodeBeforeCurrent(task, cpc)) {
                return true;
            }
        }
        return false;
    }
}
